using UnityEngine;
using System.Collections;
namespace Socket.Core
{
    using System;
    using System.Runtime.CompilerServices;
    using System.Text;

    public class ServerMessage : IMessage
    {
        private int MessageHeadCount;
        private ushort iRouteId;
        private bool route;

        public ServerMessage()
        {
            this.MessageHeadCount = 16;
            this.MethodCode = 0;
        }

        public ServerMessage(int methodCode, byte[] message, ushort iRouteId = 0)
        {
            this.MethodCode = methodCode;
            this.Body = message;
            this.iRouteId = iRouteId;
            this.MessageHeadCount = 16;
        }

        public ServerMessage(int methodCode, string message, Encoding encoding) : this(methodCode, encoding.GetBytes(message))
        {
        }

        public virtual byte[] GetReceiveBytes()
        {
            if (this.Body.Length >= this.MessageHeadCount)
            {
                int count = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToUInt16(this.Body, 0));
                this.MethodCode = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToUInt16(this.Body, 2));

                byte[] dst = new byte[count];
                Buffer.BlockCopy(this.Body, this.MessageHeadCount, dst, 0, count);
                return dst;
            }
            return null;
        }

        public virtual byte[] GetSendBytes()
        {
            byte[] buffer;
			int msgId = System.Net.IPAddress.HostToNetworkOrder((int)this.MethodCode);
			int len = System.Net.IPAddress.HostToNetworkOrder((int)(this.Body.Length + this.MessageHeadCount));
			int route=System.Net.IPAddress.HostToNetworkOrder((int)iRouteId);
            if (this.Body != null)
            {
                buffer = new byte[this.Body.Length + this.MessageHeadCount];
				buffer.GetBytes(len, 0);
            }
            else
            {
                buffer = new byte[this.MessageHeadCount];
				buffer.GetBytes(len, 0);
            }

			//buffer[0] = 1;
			//buffer[1] = 0;
           //	buffer[2] = 0;
           // buffer[3] = 0;
           // buffer[4] = 0;
           // buffer[5] = 0;
           // buffer[6] = 0;
           // buffer[7] = 0;
           //buffer[8] = 0;
          //  buffer[9] = (byte)iRouteId;
            buffer.GetBytes(msgId, 4);
			buffer.GetBytes(0, 8);
			buffer.GetBytes(route, 12);
			//int dd = buffer[0] + (buffer[1]<<8) + (buffer[2]<<16) + (buffer[3]<<24);
		//	Debug.Log(string.Format("=====GetSendBytes====== {0} {1} ", len, this.MethodCode));

            if (this.Body != null)
            {
                Buffer.BlockCopy(this.Body, 0, buffer, this.MessageHeadCount, this.Body.Length);
            }

            return buffer;
        }

        public byte[] Body { get; protected set; }

        protected int MethodCode { get; set; }
    }
}

